package com.quectel.taskserver.job.zlm;

import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.sys.SysConfigKeyConstants;
import com.quectel.sdk.zlm.ZlmMediaKitClientBuilder;
import com.quectel.sdk.zlm.basemodel.ZlmAccessConfCls;
import com.quectel.sdk.zlm.basemodel.vo.SetServerConfigResp;
import com.quectel.sdk.zlm.common.ZlmClient;
import com.quectel.sdk.zlm.constant.ZlmMediaKitConstants;
import com.quectel.sys.module.sys.service.SysConfigService;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.http.HttpRestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 在这里编写说明
 *
 * @author: rananxin
 * @email: ryan.ran@quectel.com
 * @date: 2023-01-13 13:41:00
 */
@Component
public class ZlmConfigSetTask implements SimpleJob {
    private static final HttpRestUtils HTTP_REST_UTILS = HttpRestUtils.getDefaultInstance();

    private static final Logger LOGGER = LoggerFactory.getLogger(ZlmConfigSetTask.class);

    @DubboReference
    private SysConfigService sysConfigService;

    @Override
    public void execute(ShardingContext shardingContext) {
        exec();
    }

    private void exec() {
        String configValueByKey = sysConfigService.getConfigValueByKey(SysConfigKeyConstants.ZLM_ACCESS_CONF);
        if (StringUtils.isBlank(configValueByKey)) {
            LOGGER.warn("ZLMediaKit系统参数缺失，无法同步配置...");
        }
        List<ZlmAccessConfCls> zlmAccessConfCls =
                JacksonUtils.parseArray(configValueByKey, ZlmAccessConfCls.class);

        Set<Object> objects = ConcurrentHashMap.newKeySet();
        List<ZlmAccessConfCls> distinctClsList = zlmAccessConfCls.stream()
                .filter(o -> objects.add(o.getHost()))
                .collect(Collectors.toList());

        String gatewayInnerUrl = sysConfigService.getConfigValueByKey(SysConfigKeyConstants.GATEWAY_INNER_BASE_URL);
        if (StringUtils.isBlank(gatewayInnerUrl)) {
            LOGGER.warn("ZLMediaKit配置设置，内部网关地址获取失败...");
        }

        for (ZlmAccessConfCls zlmAccessConfCl : distinctClsList) {
            try {
                ZlmClient zlmClient = ZlmMediaKitClientBuilder.builder()
                        .host(zlmAccessConfCl.getHost())
                        .secret(zlmAccessConfCl.getSecret())
                        .build();

                Map<String, Object> params = new HashMap<>();
                // 鉴权与secret设置
                params.put("secret", zlmAccessConfCl.getSecret());
                params.put("api.secret", zlmAccessConfCl.getSecret());
                params.put("api.apiDebug", 0);

                // 关闭音频转码
                params.put("protocol.enable_audio", SystemConstants.DISABLE);

                // hook相关
                params.put("hook.enable", SystemConstants.ENABLE);
                params.put("hook.on_play", gatewayInnerUrl + "dmsapi/zlm/hook/onPlay");
                params.put("hook.on_stream_not_found", gatewayInnerUrl + "dmsapi/zlm/hook/onStreamNotFound");
                params.put("hook.on_stream_none_reader", gatewayInnerUrl + "dmsapi/zlm/hook/onStreamNoneReader");
                params.put("hook.on_rtsp_realm", gatewayInnerUrl + "dmsapi/zlm/hook/onRtspRealm");

                // ffmpeg cmd模版
                params.put("ffmpeg.cmd", "%s -rtsp_transport tcp -re -i %s -c:v libx264 -f flv -an %s");

                // mediaServerId设置
                params.put("general.mediaServerId", zlmAccessConfCl.getHost());

                SetServerConfigResp setServerConfigResp = zlmClient.sendConfig(params);
                if (setServerConfigResp.getCode() == ZlmMediaKitConstants.RespCodeEnum.SUCCESS_CODE.getCode()) {
                    LOGGER.info("ZLMediaKit配置设置成功 host {} changed {}", zlmAccessConfCl.getHost(), setServerConfigResp.getChanged());
                } else {
                    LOGGER.error("ZLMediaKit配置设置异常 resp {}", setServerConfigResp);
                }
            } catch (Exception e) {
                LOGGER.error("ZLMediaKit配置设置异常", e);
            }
        }
    }
}
